import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

import 'package:flutter_localizations/flutter_localizations.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:hive/hive.dart';
import 'package:just_audio_background/just_audio_background.dart';
import 'package:netease_music_api/netease_music_api.dart';
import 'package:overlay_support/overlay_support.dart';
import 'package:path_provider/path_provider.dart';
import 'package:scoped_model/scoped_model.dart';
import 'package:shared_preferences/shared_preferences.dart';

import '/component.dart';
import '/pages/splash/page_splash.dart';

Future<void> main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await NeteaseMusicApi.init();
  await JustAudioBackground.init(
    androidNotificationChannelId: 'io.gitee.bluequantum.freesic.channel.audio',
    androidNotificationChannelName: 'Freesic playback',
    androidNotificationOngoing: true,
  );

  runApp(ProviderScope(
    child: PageSplash(
      futures: [
        SharedPreferences.getInstance(),
        getApplicationDocumentsDirectory().then((dir) {
          Hive.init(dir.path);
          return Hive.openBox<Map>('player');
        }),
        NeteaseMusicApi().usc.init()
      ],
      builder: (BuildContext context, List<dynamic> data) {
        return Container(
          child: Freesic(
            setting: Settings(data[0] as SharedPreferences),
            playerBox: data[1] as Box<Map>,
          ),
        );
      },
    ),
  ));
}

class Freesic extends ConsumerWidget {
  Freesic({
    Key? key,
    required this.setting,
    this.playerBox,
  }) : super(key: key) {
    SystemChrome.setSystemUIOverlayStyle(SystemUiOverlayStyle(
      statusBarColor: Colors.transparent,
    ));
  }

  final Settings setting;

  final Box<Map>? playerBox;

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    return ScopedModel<Settings>(
      model: setting,
      child: ScopedModelDescendant<Settings>(
        builder: (context, child, setting) {
          return Quiet(
            box: playerBox,
            child: OverlaySupport(
              child: MaterialApp(
                routes: routes,
                onGenerateRoute: routeFactory,
                title: 'Freesic',
                supportedLocales: const [Locale("en"), Locale("zh")],
                localizationsDelegates: const [
                  S.delegate,
                  GlobalWidgetsLocalizations.delegate,
                  GlobalMaterialLocalizations.delegate,
                ],
                theme: setting.theme,
                darkTheme: setting.darkTheme,
                themeMode: setting.themeMode,
                initialRoute: getInitialRoute(ref),
              ),
            ),
          );
        },
      ),
    );
  }

  String getInitialRoute(WidgetRef ref) {
    final bool login = NeteaseMusicApi().usc.isLogined;
    if (!login && !setting.skipWelcomePage) {
      return pageWelcome;
    }
    return pageMain;
  }
}
